/**
 * Created by Administrator on 2020/4/18.
 * 自定义插件
 */
layui.use(['form','layer','table'], function () {
    var form = layui.form,
        table = layui.table;
    //自定义验证规则
    form.verify({
        pass: [/^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格']
    });
    // 监听搜索操作
    form.on('submit(data-search-btn)', function (data) {
        //执行搜索重载
        table.reload('myTableElem', {
            page: {curr: 1}, where: data.field
        }, 'data');
        return false;
    });
});

var layutil = {
    confirm:function (msg, callback, cancel_callback) {
        layer.confirm(msg, {
            btn: ['确定', '取消'],
            title: "提示",
            success: function (layero, index) {
                layui.jquery(document).on('keydown', function(e){
                    if(e.keyCode == 13){
                        layui.layer.close(index);
                        typeof callback === 'function' && callback.call(this);
                        layui.jquery(document).off('keydown');
                        return;
                    }
                });
            }
        }, function (index, layero) {
            layui.layer.close(index);
            typeof callback === 'function' && callback.call(this);
        }, function () {
            typeof cancel_callback === 'function' && cancel_callback.call(this);
        });
    },
    iframe: function (title, content, checked, success_callback, end_callback) {
        layui.use(['layer'], function () {
            var layer = layui.layer,
                $ = layui.jquery;
            var index_ = layer.open({
                title: title || '新增|编辑',
                type: 2,
                shade: 0.2,
                maxmin:true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: content,
                success: function(layero, index) {
                    layer.setTop(layero);
                    if(success_callback == null && checked != null) {
                        console.log('checked', checked);
                        var body = layer.getChildFrame('body', index_);
                        for(var key in checked) {
                            body.find("input[name='"+key+"']").val(checked[key]);
                        }
                        return false;
                    }
                    typeof success_callback === 'function' && success_callback.call(this, index);
                },
                end: function () {//无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数。layer.open关闭事件
                    typeof end_callback === 'function' && end_callback.call();
                }
            });
            $(window).on("resize", function () {
                try  {
                    layer.full(index_);
                } catch (e) {

                }
            });
        });

    },
    open: function(area,content,btn,offset,yesFunc) {
        layui.use('layer', function () {
            var layer = layui.layer,
                $ = layui.$;
            layer.open({
                type: 1,
                skin: 'layui-layer-rim', //加上边框
                area: area || ['420px', '240px'], //宽高
                closeBtn: 1, //不显示关闭按钮
                anim: 2,
                shadeClose: true, //开启遮罩关闭
                content: content || '请填写内容',
                btn: btn || ['确定', '取消'],
                offset: offset || ['500px','500px'],
                success: function(layero, index){
                    $(document).on('keydown', function(e){
                        if(e.keyCode == 13){
                            layer.close(index);
                            typeof yesFunc === 'function' && yesFunc.call();
                            return;
                        }
                    })
                },
                yes: function (index) {
                    layer.close(index);
                    typeof yesFunc === 'function' && yesFunc.call();
                    return false;
                },
                btn1: function (index) {
                    layer.close(index);
                    return false;
                }
            });
            return false;
        });
    },
    post: function (url, data, success_callback, error_callback) {
        layui.jquery.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            data: data,
            contentType : 'application/json',
            headers: {'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('userdetail')).token},
            success: function (data) {
                if(success_callback == null && data.code == '0') {
                    layer.msg('操作成功', {
                        icon: 6,//成功的表情
                        time: 3000 //3秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        closeIframe();
                    });
                    return false;
                } else if(success_callback == null && data.code != '0') {
                    layer.msg(data.msg, {
                        icon: 4,//成功的表情
                        time: 3000 //3秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        closeIframe();
                    });
                    return false;
                }
                console.log('post:',data);
                typeof success_callback === 'function' && success_callback.call(this, data);
            },
            error: function (data) {
                console.log(JSON.stringify(data));
                if(error_callback == null) {
                    layer.msg('操作失败', {
                        icon: 4,//失败的表情
                        time: 3000 //3秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        closeIframe();
                    });
                    return false;
                }
                typeof error_callback === 'function' && error_callback.call(this, data);
            }
        });
    },
    postForm: function (url, data, success_callback, error_callback) {
        /*
        *   1、contentType : 'application/x-www-form-urlencoded',不能是：contentType : 'application/json'，否则后端接收到的数据为null
        *   2、data里面必须是json字符串，即var jsonStr = {"pageNum":2, "pageSize":20}格式；不能用JSON.stringify(jsonStr)来转化；否则后端接收到的数据也为null
        */
        layui.use('layer', function () {
            var $ = layui.$,
                layer = layui.layer;
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                data: data,
                contentType: 'application/x-www-form-urlencoded',
                headers: {'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('userdetail')).token},
                success: function (data) {
                    if (data.code == '0') {
                        layer.msg('操作成功', {
                            icon: 6,//成功的表情
                            time: 3000 //3秒关闭（如果不配置，默认是3秒）
                        }, function () {
                            closeIframe();
                        });
                    } else if(data.code != '0') {
                        layer.msg(data.msg, {
                            icon: 4,//成功的表情
                            time: 3000 //3秒关闭（如果不配置，默认是3秒）
                        }, function () {
                            closeIframe();
                        });
                    }
                    console.log('post:', data);
                    typeof success_callback === 'function' && success_callback.call(this, data);
                },
                error: function (data) {
                    console.log(JSON.stringify(data));
                    if (error_callback == null) {
                        layer.msg('操作失败', {
                            icon: 4,//失败的表情
                            time: 3000 //3秒关闭（如果不配置，默认是3秒）
                        }, function () {
                            closeIframe();
                        });
                        return false;
                    }
                    typeof error_callback === 'function' && error_callback.call(this, data);
                }
            });
        });
    },
    get: function (url, data, success_callback, error_callback) {
        layui.jquery.ajax({
            url: url,
            type: 'GET',
            dataType: 'json',
            data: data,
            contentType: 'application/json',
            headers: {'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('userdetail')).token},
            success: function (data) {
                typeof success_callback === 'function' && success_callback.call(this, data);
            },
            error: function (data) {
                typeof error_callback === 'function' && error_callback.call(this, data);
            }
        });
    },
    tips: function (msg, time, callback) {
        layui.use('layer', function () {
            layui.layer.msg(msg, {time: (time || 3) * 1000, shadeClose: true}, callback);
        });
    },
    success: function (msg, time, callback) {
        layui.use('layer', function () {
            layer.msg(msg||"操作成功", {
                icon: 6,time: (time || 3) * 1000, shadeClose: true
            }, function() {typeof callback === 'function' && callback.call(this)});
        });
    },
    fail: function (msg, time, callback) {
        layui.use('layer', function () {
            layer.msg(msg||"操作失败", {
                icon: 4,time: (time || 3) * 1000, shadeClose: true
            }, function() {typeof callback === 'function' && callback.call(this)});
        });
    },
    menuSelector: function (defaultMenu, callback) {//菜单选择器(defaultMenu默认选中节点 callback回调方法)
        layui.use(['layer', 'form'], function () {
            var layer = layui.layer,
                form = layui.form;
            var index = layer.open({
                area: ['600px', '600px'],
                title: '请选择菜单',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                btn: ['确定','取消'],
                content: '/page/selector/menu-selector.html',
                success: function() {
                    var body = layer.getChildFrame('body', index);
                    var id = defaultMenu.id || '';
                    //console.log(defaultMenu);
                    localStorage.setItem("selector-menu-id", id);
                    form.render();
                },
                end: function () {//无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数。layer.open关闭事件
                    localStorage.removeItem("selector-menu-title");
                    localStorage.removeItem("selector-menu-id");
                    localStorage.removeItem("selector-menu-pid");
                },
                yes: function (index) {
                    layer.close(index);
                    var title= localStorage.getItem("selector-menu-title");
                    var id = localStorage.getItem("selector-menu-id");
                    var pid = localStorage.getItem("selector-menu-pid");
                    var res = {title: title,id: id,pid: pid};
                    typeof callback === 'function' && callback.call(this, res);
                    return false;
                },
                btn1: function (index) {
                    layer.close(index);
                    return false;
                }
            });
        });

    },
    table: function (url,cols,callback) {
        layui.use(['form', 'table', 'slider'], function () {
            var $ = layui.jquery,
                table = layui.table;
            table.render({
                elem: '#myTableElem',
                url: url,
                toolbar: '#myToolbarElem',
                headers:{'Accept': 'application/json','Authorization':'Bearer '+ JSON.parse(localStorage.getItem('userdetail')).token},
                cols: cols,
                limits: [10, 15, 20, 25, 50, 100],
                limit: 15,
                page: true,
                parseData: function (res) {
                    console.log("res", res);
                    if(res.code == 401) window.location = '/page/login-1.html';
                },
            });
        });
    }
};

function closeIframe() {
    try {
        var iframeIndex = parent.layer.getFrameIndex(window.name);
        parent.layer.close(iframeIndex);
    } catch (e) {}
}